<template>
  <el-dialog v-model="dialogVisible" :title="formType == 'create' ? '新增土地基础信息' : '编辑土地基础信息'" width="1200px" append-to-body>
    <div class="kuaicenter">
      <div class="kuai"></div>
      <h2>基础信息</h2>
    </div>
    <el-form ref="informationFormRef" v-loading="formLoading" :disabled="disabled" :model="formData" :rules="formRules" label-width="80px">
      <el-row :gutter="24">
        <el-col :span="6">
          <el-form-item label="土地名称" prop="form.lanName">
            <el-input v-model="formData.form.lanName" placeholder="请输入土地名称" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="宗地编号" prop="form.parcelCode">
            <el-input v-model="formData.form.parcelCode" placeholder="请输入宗地编号" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="地块位置" prop="form.plotLocation">
            <el-input v-model="formData.form.plotLocation" placeholder="请输入地块位置" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="土地面积" prop="form.landArea">
            <el-input v-model="formData.form.landArea" placeholder="请输入土地面积" />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="受让单位" prop="form.transferee">
            <el-input v-model="formData.form.transferee" placeholder="请输入受让单位" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="土地用途" prop="form.landuse">
            <el-select v-model="formData.form.landuse" placeholder="请选择土地用途">
              <el-option v-for="dict in land_use" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="租赁状态" prop="form.leaseStatus">
            <el-select
              v-model="formData.form.leaseStatus"
              placeholder="请选择租赁状态"
              :disabled="disableLeaseStatus"
            >
              <el-option v-for="dict in land_ease_status" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="抵押状态" prop="form.collateralStatus">
            <el-select v-model="formData.form.collateralStatus" placeholder="请选择抵押状态">
              <el-option v-for="dict in land_collateral_status" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="开发状态" prop="form.developmenStatus">
            <el-select v-model="formData.form.developmenStatus" placeholder="请选择开发状态">
              <el-option v-for="dict in land_developmen_status" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="项目名称" prop="form.projectName">
            <el-input v-model="formData.form.projectName" placeholder="请输入项目名称" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="开工日期" prop="form.commencementDate">
            <el-date-picker v-model="formData.form.commencementDate" clearable type="date" value-format="YYYY-MM-DD" placeholder="请选择开工日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="竣工日期" prop="form.completionDate">
            <el-date-picker v-model="formData.form.completionDate" clearable type="date" value-format="YYYY-MM-DD" placeholder="请选择竣工日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="地块备注" prop="form.remarks">
            <el-input v-model="formData.form.remarks" placeholder="请输入地块备注" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="地块估值" prop="form.estimation">
            <el-input v-model="formData.form.estimation" placeholder="请输入地块估值" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="附件" prop="form.attachment">
            <file-upload v-model="formData.form.attachment" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="实景图片" prop="form.realPictures">
            <image-upload v-model="formData.form.realPictures" />
          </el-form-item>
        </el-col>
      </el-row>
      <template v-if="showLeaseInfo">
        <div class="kuaicenter">
          <div class="kuai"></div>
          <h2>租赁信息</h2>
        </div>
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="承&nbsp;&nbsp;租&nbsp;&nbsp;人" prop="initLeaseForm.lessee">
              <el-input v-model="formData.initLeaseForm.lessee" placeholder="请输入承租人" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="缴租频次" prop="initLeaseForm.frequencyOfRentPayments">
              <el-select v-model="formData.initLeaseForm.frequencyOfRentPayments" placeholder="请选择缴租频次">
                <el-option v-for="dict in land_frequency_of_rent_payments" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="租金(万)" prop="initLeaseForm.rents">
              <el-input v-model="formData.initLeaseForm.rents" placeholder="请输入租金(万元)" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联&nbsp;&nbsp;系&nbsp;&nbsp;人" prop="initLeaseForm.associates">
              <el-input v-model="formData.initLeaseForm.associates" placeholder="请输入联系人" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系电话" prop="initLeaseForm.contactInformation">
              <el-input v-model="formData.initLeaseForm.contactInformation" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="开始时间" prop="initLeaseForm.startTime">
              <el-date-picker v-model="formData.initLeaseForm.startTime" clearable type="date" value-format="YYYY-MM-DD" placeholder="请选择开始时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="结束时间" prop="initLeaseForm.endTime">
              <el-date-picker v-model="formData.initLeaseForm.endTime" clearable type="date" value-format="YYYY-MM-DD" placeholder="请选择结束时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="租&nbsp;&nbsp;期(年)" prop="leaseTerm">
              <el-input v-model="formData.initLeaseForm.leaseTerm" placeholder="自动计算租期" readonly :disabled="true" />
            </el-form-item>
          </el-col>
        </el-row>
        <div class="kuaicenter">
          <div class="kuai"></div>
          <h2>收租计划</h2>
        </div>
        <div>
          <div v-if="formData.rentCollectionPlan == null || formData.rentCollectionPlan.length === 0" style="text-align: right">
            <el-button :loading="buttonLoading" type="primary" @click="handlePush">辅助生成</el-button>
          </div>
          <H2 class="mb-5" style="text-align: center; font-weight: bold">收租计划信息</H2>
          <el-table :data="formData.rentCollectionPlan" style="width: 100%" :show-summary="true" :summary-method="getSummaries">
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column prop="dueDate" label="应收日期">
              <template #default="scope">
                <el-date-picker v-model="scope.row.dueDate" value-format="YYYY-MM-DD" type="date" />
              </template>
            </el-table-column>

            <el-table-column prop="rentReceivable" label="应收租金(元)">
              <template #default="scope">
                <el-input type="number" v-model="scope.row.rentReceivable" class="cell-input" />
              </template>
            </el-table-column>
            <el-table-column prop="collect" label="是否收取" width="160">
              <template #default="scope">
                <el-radio-group v-model="scope.row.collect">
                  <el-radio :value="false" size="large">否</el-radio>
                  <el-radio :value="true" size="large">是</el-radio>
                </el-radio-group>
              </template>
            </el-table-column>
            <el-table-column prop="paidInTime" label="实收日期">
              <template #default="scope">
                <el-date-picker v-model="scope.row.paidInTime" value-format="YYYY-MM-DD" type="date" />
              </template>
            </el-table-column>
            <el-table-column width="110" label="操作" align="center" class-name="small-padding fixed-width">
              <template #default="scope">
                <div v-if="disabled">-</div>
                <div v-else>
                  <el-button link type="primary" @click="handlePush(scope.$index)">新增</el-button>
                  <el-button link type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </template>
      <template v-else>
        <el-empty description="请将租赁状态修改为已租赁以添加租赁信息和收租计划" :image-size="200" />
      </template>
    </el-form>
    <template v-if="!disabled" #footer>
      <div class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">保 存</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" name="SystemRoleForm" setup>
import {
  getInformation,
  addInformation,
  updateInformation,
  addRentCollectionPlan,
  rentCollectionPlanList,
  updateRentCollectionPlan,
  delrentCollectionPlan
} from '@/api/zichanguanli/information';
import { getLeaseInformation, addLeaseInformation, updateLeaseInformation } from '@/api/zichanguanli/leaseInformation';
import { validateNumber, validateInteger } from '@/utils/formRules';
import { generateRentPlan, generateSingleRentPlan } from '@/utils/genRentProject';
import { ElMessage } from 'element-plus';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { land_ease_status, land_use, land_developmen_status, land_collateral_status, land_frequency_of_rent_payments } = toRefs<any>(
  proxy?.useDict('land_ease_status', 'land_use', 'land_developmen_status', 'land_collateral_status', 'land_frequency_of_rent_payments')
);

const disabled: any = ref(false); // 表单是否禁用
const buttonLoading = ref(false); // 按钮的 loading
const dialogVisible = ref(false); // 弹窗的是否展示
const formLoading = ref(false); // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref(''); // 表单的类型：create - 新增；update - 修改

const disableLeaseStatus = ref(false); // 租赁状态是否禁用

const formData: any = ref({
  form: {
    id: undefined,
    lanName: undefined,
    parcelCode: undefined,
    plotLocation: undefined,
    landArea: undefined,
    transferee: undefined,
    landuse: undefined,
    leaseStatus: undefined,
    collateralStatus: undefined,
    developmenStatus: undefined,
    projectName: undefined,
    commencementDate: undefined,
    completionDate: undefined,
    remarks: undefined,
    estimation: undefined,
    attachment: undefined,
    realPictures: undefined
  },
  initLeaseForm: {
    id: undefined,
    lessee: undefined,
    frequencyOfRentPayments: undefined,
    rents: undefined,
    associates: undefined,
    contactInformation: undefined,
    leaseTerm: undefined,
    startTime: undefined,
    endTime: undefined
  },
  rentCollectionPlan: []
});
const formRules = reactive({
  'form.lanName': [{ required: true, message: '土地名称不能为空', trigger: 'blur' }],
  'form.parcelCode': [{ required: true, message: '宗地编号不能为空', trigger: 'blur' }],
  'form.plotLocation': [{ required: true, message: '地块位置不能为空', trigger: 'blur' }],
  'form.landArea': [
    { required: true, message: '土地面积不能为空', trigger: 'blur' },
    { validator: validateNumber, trigger: 'blur' }
  ],
  'form.transferee': [{ required: true, message: '受让单位不能为空', trigger: 'blur' }],
  'form.leaseStatus': [{ required: true, message: '租赁状态不能为空', trigger: 'change' }],
  'form.estimation': [{ validator: validateNumber, trigger: 'blur' }],
  'initLeaseForm.lessee': [{ required: true, message: '承租人不能为空', trigger: 'blur' }],
  'initLeaseForm.frequencyOfRentPayments': [{ required: true, message: '缴租频次不能为空', trigger: 'change' }],
  'initLeaseForm.rents': [
    { required: true, message: '租金不能为空', trigger: 'blur' },
    { validator: validateNumber, message: '请输入合法的数字', trigger: 'blur' }
  ],
  'initLeaseForm.contactInformation': [
    { required: true, message: '联系方式不能为空', trigger: 'blur' },
    {  required: true, message: '请填写正确的手机号码', trigger: 'change' }
  ],
  'initLeaseForm.startTime': [{ required: true, message: '开始时间不能为空', trigger: 'change' }],
  'initLeaseForm.endTime': [{ required: true, message: '结束时间不能为空', trigger: 'change' }],
  'initLeaseForm.associates': [{ required: true, message: '联系人不能为空', trigger: 'blur' }]
});
const informationFormRef = ref(); // 表单 Ref

const handlePush = (index?: number) => {
  // 如果传入了 index，说明是在指定位置插入新记录
  if (typeof index === 'number') {
    // 确保 rentCollectionPlan 存在
    if (!formData.value.rentCollectionPlan) {
      formData.value.rentCollectionPlan = [];
    }

    // 生成新的收租计划记录
    const newPlan = generateSingleRentPlan();

    // 在指定位置后插入新记录
    formData.value.rentCollectionPlan.splice(index + 1, 0, newPlan);
    ElMessage.success('添加成功');
    return;
  }

  // 以下是原有的批量生成逻辑
  const leaseForm = formData.value?.initLeaseForm;
  if (!leaseForm) {
    ElMessage.warning('租赁信息不存在');
    return;
  }

  const { frequencyOfRentPayments, rents, startTime, endTime } = leaseForm;

  // 检查所有必要字段
  if (!frequencyOfRentPayments) {
    ElMessage.warning('请先填写缴租频次');
    return;
  }
  if (!rents) {
    ElMessage.warning('请先填写租金');
    return;
  }
  if (!startTime) {
    ElMessage.warning('请先填写开始时间');
    return;
  }
  if (!endTime) {
    ElMessage.warning('请先填写结束时间');
    return;
  }

  console.log(formData.value.initLeaseForm);

  // 生成收租计划
  try {
    const rentPlans = generateRentPlan({
      frequencyOfRentPayments,
      rents: Number(rents),
      startTime,
      endTime,
      transform: true
    });

    // 确保 formData.value 存在
    if (!formData.value) {
      ElMessage.error('表单数据不存在');
      return;
    }

    // 更新表格数据
    formData.value.rentCollectionPlan = rentPlans;
    ElMessage.success('收租计划生成成功');
  } catch (error) {
    console.error('生成收租计划失败:', error);
    ElMessage.error('生成收租计划失败，请检查输入数据');
  }
};

const handleDelete = async (index: number, row: any) => {
  if (row.id) {
    await delrentCollectionPlan(row.id);
    formData.value.rentCollectionPlan.splice(index, 1);
  } else {
    formData.value.rentCollectionPlan.splice(index, 1);
  }
};

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true;
  formType.value = type;
  disabled.value = false;
  resetForm();
  // 修改时，设置数据
  if (type === 'detail') {
    disabled.value = true;
  }
  if (id) {
    formLoading.value = true;
    try {
      const res = await getInformation(id);

      const dadas = { ...res.data };
      formData.value.form = dadas.landInformationDetailVO;
      formData.value.initLeaseForm = dadas.landLeaseInformationDetailVO || {};
      formData.value.rentCollectionPlan = dadas.rentPlanDetailVOList || [];
      disableLeaseStatus.value = formData.value.form.leaseStatus == '1';
    } finally {
      formLoading.value = false;
    }
  }
};

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    form: {
      id: undefined,
      lanName: undefined,
      parcelCode: undefined,
      plotLocation: undefined,
      landArea: undefined,
      transferee: undefined,
      landuse: undefined,
      leaseStatus: '2',
      collateralStatus: undefined,
      developmenStatus: undefined,
      projectName: undefined,
      commencementDate: undefined,
      completionDate: undefined,
      remarks: undefined,
      estimation: undefined,
      attachment: undefined,
      realPictures: undefined
    },
    initLeaseForm: {
      landInfoId: undefined,
      lessee: undefined,
      frequencyOfRentPayments: undefined,
      rents: undefined,
      associates: undefined,
      contactInformation: undefined,
      leaseTerm: undefined,
      startTime: undefined,
      endTime: undefined
    },
    rentCollectionPlan: []
  };
  informationFormRef.value?.resetFields();
  disableLeaseStatus.value = false;
};
defineExpose({ open }); // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']); // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  const valid = await informationFormRef.value.validate();
  if (!valid) return;
  // 提交请求
  formLoading.value = true;
  try {
    let type = '';
    if (formType.value === 'create') {
      type = 'create';
      if (formData.value.rentCollectionPlan.length !== 0) {
        formData.value.rentCollectionPlan.map((item: any) => {
          item.rentReceivable = Number(item.rentReceivable);
        });
      }
      formData.value.form.landArea = Number(formData.value.form.landArea);
      formData.value.form.estimation = Number(formData.value.form.estimation);
      formData.value.initLeaseForm.rents = Number(formData.value.initLeaseForm.rents);
      const datas = {
        landInformationAddBo: formData.value.form,
        landLeaseInformationAddBo: formData.value.initLeaseForm,
        rentPlanAddBoList: formData.value.rentCollectionPlan
      };
      await addInformation(datas);
    } else {
      type = 'update';
      if (formData.value.rentCollectionPlan != null && formData.value.rentCollectionPlan.length !== 0) {
        formData.value.rentCollectionPlan.map((item: any) => {
          item.rentReceivable = Number(item.rentReceivable);
        });
      } else {
        formData.value.rentCollectionPlan = [];
      }
      formData.value.form.landArea = Number(formData.value.form.landArea);
      formData.value.form.estimation = Number(formData.value.form.estimation);
      formData.value.initLeaseForm.rents = Number(formData.value.initLeaseForm.rents);
      const datas = {
        landInformationEditBo: formData.value.form,
        landLeaseInformationEditBo: formData.value.initLeaseForm,
        rentPlanAddBoList: formData.value.rentCollectionPlan
      };
      await updateInformation(datas);
    }
    dialogVisible.value = false;
    // 发送操作成功的事件
    emit('success', type);
  } finally {
    formLoading.value = false;
  }
};

// 修改 watch 逻辑，确保精确计算
watch([() => formData.value.initLeaseForm.startTime, () => formData.value.initLeaseForm.endTime], ([newStartTime, newEndTime]) => {
  if (newStartTime && newEndTime) {
    const startDate = new Date(newStartTime);
    const endDate = new Date(newEndTime);

    // 确保结束时间大于开始时间
    if (endDate <= startDate) {
      formData.value.initLeaseForm.endTime = null;
      formData.value.initLeaseForm.leaseTerm = undefined;
      ElMessage.warning('结束时间必须大于开始时间');
      return;
    }

    // 计算精确的年份差值
    const diffTime = Math.abs(endDate - startDate);
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
    const years = diffDays / 365;

    // 四舍五入到一位小数
    formData.value.initLeaseForm.leaseTerm = Math.round(years * 10) / 10;
  } else {
    formData.value.initLeaseForm.leaseTerm = undefined;
  }
});

const getSummaries = (param: any) => {
  const { columns, data } = param;
  const sums: any[] = [];
  columns.forEach((column: any, index: number) => {
    if (index === 0) {
      sums[index] = '合计';
      return;
    }
    if (index === 2) {
      // 应收租金列的索引
      const values = data.map((item: any) => Number(item.rentReceivable) || 0);
      sums[index] = values.reduce((prev: number, curr: number) => {
        return prev + curr;
      }, 0);
      // 格式化数字，保留2位小数
      sums[index] = sums[index].toFixed(2);
    } else {
      sums[index] = '';
    }
  });
  return sums;
};

// 添加一个计算属性来判断是否显示租赁相关信息
const showLeaseInfo = computed(() => {
  return formData.value.form.leaseStatus === '1'; // 假设 '1' 代表已租赁状态
});

// 监听租赁状态变化
watch(
  () => formData.value.form.leaseStatus,
  (newStatus) => {
    if (newStatus !== '1') {
      // 如果切换到非已租赁状态，清空租赁信息和收租计划
      formData.value.initLeaseForm = {
        landInfoId: undefined,
        lessee: undefined,
        frequencyOfRentPayments: undefined,
        rents: undefined,
        associates: undefined,
        contactInformation: undefined,
        leaseTerm: undefined,
        startTime: undefined,
        endTime: undefined
      };
      formData.value.rentCollectionPlan = [];
    }
  }
);
</script>
